<template>
  <!-- 表头按钮 -->
  <slot>
    <a-button type="primary" @click="visible = true">表头设置</a-button>
  </slot>
  <!-- 窗口 -->
  <a-drawer :width="'50%'" v-model:visible="visible" unmountOnClose :title="props.title">
    <template #footer>
      <a-space>
        <a-button @click="visible = false">取消</a-button>
        <a-button type="primary" @click="handleOk">确定</a-button>
      </a-space>
    </template>
    <div class="draggable">
      <div class="draggable-selected">
        <h3>已选择的表头：</h3>
        <!-- 可拖拽的组件 -->
        <draggable class="item" :list="selectedHeaders" ghost-class="ghost" handle=".move" filter=".forbid" :force-fallback="true" chosen-class="chosenClass" animation="300" itemKey="name" :fallback-class="true" :fallback-on-body="true" :touch-start-threshold="10" :fallback-tolerance="10" :sort="true">
          <template #item="{ element, rowIndex }">
            <div class="item-box">
              <a-button-group>
                <a-button :class="forbidList.includes(element.code) ? 'forbid' : 'move'">
                  {{ element.name }}
                </a-button>
                <a-button @click="removeHeader(element, rowIndex)" v-if="forbidList.includes(element.code) ? false : true">
                  <icon-close-circle />
                </a-button>
              </a-button-group>
            </div>
          </template>
        </draggable>
      </div>
      <div class="draggable-unselected">
        <h3>未选择的表头：</h3>
        <div class="item">
          <div class="item-box" v-for="(item, index) in unselectedHeaders" :key="item.code">
            <a-button @click="addHeader(item, index)">
              {{ item.name }}
            </a-button>
          </div>
        </div>
      </div>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch, watchEffect } from 'vue';
import Draggable from 'vuedraggable'; //引入可拖拽组件
import {
  GetContractHeader,
  PutContractHeader,
} from '@/api/contract-management/contract-list/index';
import { formHeaderSettingList } from '@/types/global'; //引入类型

const loginInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);
// 子组件
const props = withDefaults(
  // 参数说明
  defineProps<{
    headerValues: formHeaderSettingList[];
    defineHeaders?: formHeaderSettingList[];
    title?: string; // 标题
    type: number;
    forbidList?: string[]; // 不准移动和删除的表头
  }>(),
  {
    title: '表头设置',
    forbidList: () => [],
  }
);
const headerList = ref<formHeaderSettingList[]>(
  props.defineHeaders?.map((item) => {
    return { ...item, isDefault: 1 };
  }) || []
);
// 未选择的表头
const unselectedHeaders = ref<formHeaderSettingList[]>([]);
// 已选择的表头
const selectedHeaders = ref<formHeaderSettingList[]>([]);

// 去除一个表头
const removeHeader = (header: formHeaderSettingList, index: number) => {
  selectedHeaders.value.splice(index, 1);
  unselectedHeaders.value.push({
    ...header,
    isDefault: 2,
  });
};

// 添加一个表头
const addHeader = (header: formHeaderSettingList, index: number) => {
  unselectedHeaders.value.splice(index, 1);
  selectedHeaders.value.push({
    ...header,
    isDefault: 1,
  });
};
// 子组件方法
let emit = defineEmits(['update:headerValues']);
// 刷新
let loadList = () => {
  selectedHeaders.value = headerList.value.filter(
    ({ isDefault }) => isDefault === 1
  );
  unselectedHeaders.value = headerList.value.filter(
    ({ isDefault }) => isDefault === 2
  );
  emit(
    'update:headerValues',
    selectedHeaders.value.map((item) => {
      return { ...item };
    })
  );
};

let visible = ref(false);
// 确定按钮
const handleOk = async () => {
  try {
    let list = [...unselectedHeaders.value, ...selectedHeaders.value];
    await PutContractHeader({
      type: props.type,
      userId: loginInfo.userId,
      extend: JSON.stringify(list),
    });
    loadList();
    headerList.value = list;
    visible.value = false;
  } catch (err) {
    console.log(err);
  }
};
// 按钮状态变化时
watch(visible, () => {
  if (!visible.value) loadList();
});
// 获取数据
const getHeaders = async () => {
  try {
    const tableHead = await GetContractHeader({
      type: props.type,
      userId: loginInfo.userId,
    });
    if (tableHead.extends) {
      headerList.value = tableHead.extends || [];
      loadList();
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
getHeaders();
loadList();
</script>

<style scoped lang="less">
.draggable {
  &-selected {
    border-bottom: 1px solid #ccc;
    padding-bottom: 20px;
  }
  &-selected,
  &-unselected {
    .item {
      display: flex;
      flex-wrap: wrap;

      &-box {
        margin: 0 10px 10px 0;
      }
    }
  }
}
</style>
